<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>创建年终报告</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/css/bootstrap-icons.css" rel="stylesheet">
    <link href="/css/sweetalert2.min.css" rel="stylesheet">
    <link href="/css/select2.min.css" rel="stylesheet" />
    <style>
        .user-menu {
            position: fixed;
            top: 1rem;
            right: 1rem;
            z-index: 9999;
        }
        .change-password-modal .modal-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        .password-requirements {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }
        .alert-float {
            /* position: fixed; */
            top: 1rem;
            right: 1rem;
            z-index: 9998;
            /* min-width: 300px; */
            width: 700px;
            display: none;
            text-align: center;
        }
        .alert-container {
            text-align: center; /* 水平居中 */
        }

        .alert.alert-float {
            display: inline-block; /* 使 margin: 0 auto 生效 */
            margin: 0 auto; /* 水平居中 */
        }
        .dropdown-menu {
            z-index: 9999;
        }
        .modal {
            z-index: 10000;
        }
        .navbar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 600;
            color: #4f46e5;
        }

        .nav-link {
            color: #4b5563;
            transition: all 0.3s ease;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
        }

        .nav-link:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        .nav-link.active {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        .navbar-toggler {
            border: none;
            padding: 0.5rem;
        }

        .navbar-toggler:focus {
            box-shadow: none;
            outline: none;
        }

        .dropdown-menu {
            border: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
        }

        .dropdown-item {
            padding: 0.5rem 1rem;
            color: #4b5563;
            transition: all 0.3s ease;
        }

        .dropdown-item:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        @media (max-width: 768px) {
            .navbar-nav {
                padding: 1rem 0;
            }
            .nav-link {
                padding: 0.5rem 1rem;
            }
        }
        .swal2-container {
            z-index: 10000 !important;
        }

        .modal-backdrop {
            z-index: 9999 !important;
        }

        .modal {
            z-index: 10000 !important;
        }
        .select2-container {
            width: 100% !important;
        }
        .select2-selection {
            height: 38px !important;
            padding: 5px !important;
            border: 1px solid #ced4da !important;
            border-radius: 0.375rem !important;
        }
        .select2-selection__arrow {
            height: 36px !important;
        }
    </style>
</head>
<body>
    <div class="page-background bg-index"></div>
    <div class="wave-bottom"></div>

    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg sticky-top">
        <div class="container">
            <a class="navbar-brand" href="/index">
                <i class="bi bi-clipboard-data me-2"></i>运维年报系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <i class="bi bi-list"></i>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/index">
                            <i class="bi bi-house me-1"></i>首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/hospitals/hospital-import">
                            <i class="bi bi-hospital me-1"></i>医院管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/report-list">
                            <i class="bi bi-file-text me-1"></i>报告列表
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/yearEndReview">
                            <i class="bi bi-file-text me-1"></i>值班表生成
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-1"></i>
                            <span th:text="${userName}">用户名</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="#" onclick="openChangePasswordModal()">
                                    <i class="bi bi-key me-2"></i>修改密码
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item text-danger" href="/logout">
                                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                                </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 修改密码模态框 -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">修改密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">原密码</label>
                        <input type="password" class="form-control" id="oldPassword">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">确认新密码</label>
                        <input type="password" class="form-control" id="confirmPassword">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="changePassword()">确认修改</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 浮动提示框 -->
<!--    <div class="alert alert-float" role="alert"></div>-->
    <div class="alert-container">
        <div class="alert alert-float" role="alert"></div>
    </div>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="bi bi-file-earmark-text me-2"></i>创建年终报告
                </h3>
            </div>
            <div class="card-body">
                <form id="reportForm" th:action="@{/reports}" method="post" enctype="multipart/form-data">
                    <div class="row">
                        <!-- 基本信息 -->
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-building me-2"></i>医院名称
                            </label>
                            <select class="form-select" id="hospitalSelect" required>
                                <option value="">请选择医院</option>
                            </select>
                            <input type="hidden" id="hospitalId" name="hospitalId">
                            <input type="hidden" id="hospitalName" name="hospitalName">
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-calendar me-2"></i>年度
                            </label>
                            <select class="form-select" name="demandYear" required>
                                <option value="">请选择年度</option>
                            </select>
                        </div>

                        <!-- 运维数据 -->

                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                <i class="bi bi-calendar-check me-2"></i>年度最晚运维服务时间
                            </label>
                            <input type="datetime-local" class="form-control" name="lastOpsTime" required>
                        </div>

                        <!-- 补充说明 -->
<!--                        <div class="col-12 mb-3">-->
<!--                            <label class="form-label">-->
<!--                                <i class="bi bi-chat-text me-2"></i>补充说明-->
<!--                            </label>-->
<!--                            <textarea class="form-control" name="description" rows="3"></textarea>-->
<!--                        </div>-->

                        <!-- Excel导入 -->
                        <div class="col-12 mb-3">
                            <label class="form-label" style="display: flex;align-items: center;">
                                <i class="bi bi-file-earmark-excel me-2"></i>导入故障记录Excel文件
                                <a href="../excel/故障列表导入.xlsx" class="btn btn-outline-primary" style="margin-left: 20px;height: 40px;display: flex;align-items: center; width: 220px;">
                                    <i class="bi bi-download me-2"></i>下载故障导入模板
                                </a>
                            </label>
                            <input type="file" class="form-control" name="faultFile" accept=".xlsx,.xls">
                        </div>

                        <!-- Excel导入 -->
                        <div class="col-12 mb-3">
                            <label class="form-label" style="display: flex;align-items: center;">
                                <i class="bi bi-file-earmark-excel me-2"></i>导入运维工作清单Excel文件
                                <a href="../excel/需求列表导入.xlsx" class="btn btn-outline-primary" style="margin-left: 20px;height: 40px;display: flex;align-items: center; width: 180px;">
                                    <i class="bi bi-download me-2"></i>下载导入模板
                                </a>
                            </label>
                            <input type="file" class="form-control" name="file" accept=".xlsx,.xls">
                        </div>

                        <!-- 巡检情况 -->
                        <div class="col-12 mb-3">
                            <h5 class="border-bottom pb-2">
                                <i class="bi bi-clipboard-check me-2"></i>巡检情况
                            </h5>
                        </div>

                        <!-- 线上巡检 -->
                        <div class="col-md-6 mb-3">
                            <label class="form-label">线上巡检人员投入</label>
                            <input type="number" class="form-control" name="onlineInspectionStaff" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">线上巡检频次（一月/N次）</label>
                            <input type="number" class="form-control" name="onlineInspectionFrequency" required>
                        </div>

                        <!-- 线下巡检 -->
                        <div class="col-md-6 mb-3">
                            <label class="form-label">线下巡检人员投入</label>
                            <input type="number" class="form-control" name="offlineInspectionStaff" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">线下巡检频次（一天/N次）</label>
                            <input type="number" class="form-control" name="offlineInspectionFrequency" required>
                        </div>

                        <!-- 巡检记录导入 -->
                        <div class="col-12 mb-3">
                            <label class="form-label" style="display: flex;align-items: center;">
                                <i class="bi bi-file-earmark-excel me-2"></i>导入巡检记录Excel文件
                                <a href="../excel/巡检列表导入.xlsx" class="btn btn-outline-primary" style="margin-left: 20px;height: 40px;display: flex;align-items: center; width: 180px;">
                                    <i class="bi bi-download me-2"></i>下载导入模板
                                </a>
                            </label>
                            <input type="file" class="form-control" name="inspectionFile" accept=".xlsx,.xls">
                        </div>
                    </div>

                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="bi bi-check-lg me-2"></i>生成报告
                        </button>
                    </div>
                </form>

                <div id="reportLinkSection" class="mt-4" style="display: none;">
                    <div class="alert alert-success">
                        <h4 class="alert-heading">
                            <i class="bi bi-check-circle-fill me-2"></i>报告已生成！
                        </h4>
                        <p class="mb-0">您可以通过以下链接访问报告：</p>
                        <div class="input-group mt-3">
                            <input type="text" class="form-control" id="reportLink" readonly>
                            <button class="btn btn-outline-success" type="button" onclick="copyReportLink()">
                                <i class="bi bi-clipboard me-2"></i>复制链接
                            </button>
                            <a id="viewReportBtn" href="#" class="btn btn-success" target="_blank">
                                <i class="bi bi-eye me-2"></i>查看报告
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 确保 Bootstrap JS 和其他必要的脚本在最后加载 -->
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/sweetalert2.js"></script>
    <script src="/js/select2.min.js"></script>

    <script>
        // 修改密码模态框实例
        let changePasswordModal;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
        });

        // 打开修改密码模态框
        function openChangePasswordModal() {
            if (changePasswordModal) {
                changePasswordModal.show();
            }
        }

        function showAlert(message, type = 'success') {
            const alert = document.querySelector('.alert-float');
            alert.className = `alert alert-float alert-${type}`;
            alert.textContent = message;
            alert.style.display = 'block';
            setTimeout(() => {
                alert.style.display = 'none';
            }, 3000);
        }

        function validatePassword(password) {
            const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
            return regex.test(password);
        }

        function changePassword() {
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // 清空输入框
            function clearInputs() {
                document.getElementById('oldPassword').value = '';
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmPassword').value = '';
            }

            // 验证输入
            if (!oldPassword || !newPassword || !confirmPassword) {
                Swal.fire({
                    icon: 'warning',
                    title: '请填写完整',
                    text: '请填写所有密码字段',
                    confirmButtonText: '确定'
                });
                return;
            }

            if (newPassword !== confirmPassword) {
                Swal.fire({
                    icon: 'error',
                    title: '密码不匹配',
                    text: '新密码与确认密码不一致',
                    confirmButtonText: '确定'
                });
                clearInputs();
                return;
            }

            // 验证密码强度
            if (!validatePassword(newPassword)) {
                Swal.fire({
                    icon: 'error',
                    title: '密码强度不足',
                    text: '密码必须包含大小写字母和数字，且长度至少为8位',
                    confirmButtonText: '确定'
                });
                clearInputs();
                return;
            }

            // 显示加载中
            Swal.fire({
                title: '处理中...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // 发送修改密码请求
            fetch('/api/user/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    oldPassword: oldPassword,
                    newPassword: newPassword
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭修改密码模态框
                    if (changePasswordModal) {
                        changePasswordModal.hide();
                    }

                    // 清空输入
                    clearInputs();

                    // 显示成功消息并跳转
                    Swal.fire({
                        icon: 'success',
                        title: '修改成功',
                        text: '密码已成功修改，请重新登录',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        confirmButtonText: '确定'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '/logout';
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '修改失败',
                        text: data.message || '原密码错误或系统异常，请重试',
                        confirmButtonText: '确定'
                    });
                    clearInputs();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '系统错误',
                    text: '发生未知错误，请重试',
                    confirmButtonText: '确定'
                });
                clearInputs();
            });
        }

        $(document).ready(function() {
            $('#reportForm').on('submit', function(e) {
                e.preventDefault();

                // 显示加载提示
                Swal.fire({
                    title: '正在生成报告',
                    html: '请稍候...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 获取表单数据（除Excel文件外）
                const formData = new FormData(this);
                const reportData = {
                    hospitalName: formData.get('hospitalName'),
                    hospitalId: formData.get('hospitalId'),
                    demandYear: parseInt(formData.get('demandYear')),
                    // totalRequests: parseInt(formData.get('totalRequests')),
                    // totalOpsHours: parseFloat(formData.get('totalOpsHours')),
                    lastOpsTime: formData.get('lastOpsTime'),
                    description: formData.get('description'),
                    // totalFaults: parseInt(formData.get('totalFaults')),
                    // thirdPartyFaults: parseInt(formData.get('thirdPartyFaults')),
                    // thirdPartyResolvedFaults: parseInt(formData.get('thirdPartyResolvedFaults')),
                    // internalFaults: parseInt(formData.get('internalFaults')),
                    // internalResolvedFaults: parseInt(formData.get('internalResolvedFaults')),
                    // 添加巡检相关字段
                    onlineInspectionStaff: parseInt(formData.get('onlineInspectionStaff')),
                    onlineInspectionFrequency: parseInt(formData.get('onlineInspectionFrequency')),
                    offlineInspectionStaff: parseInt(formData.get('offlineInspectionStaff')),
                    offlineInspectionFrequency: parseInt(formData.get('offlineInspectionFrequency')),
                    patientGuidanceCount: parseInt(formData.get('patientGuidanceCount')),
                    reportUrl: window.location.protocol+"//"+window.location.host + `/homePage/`
                };

                // 第一步：保存报告基本信息
                $.ajax({
                    url: '/api/reports',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(reportData),
                    success: function(response) {
                        if (response && response.id) {
                            let uploadCount = 0;
                            let successCount = 0;
                            const totalUploads = 3; // 需要上传的文件数量

                            // 检查是否有需求清单文件
                            const excelFile = formData.get('file');
                            if (excelFile && excelFile.size > 0) {
                                const excelFormData = new FormData();
                                excelFormData.append('file', excelFile);
                                excelFormData.append('reportId', response.id);
                                excelFormData.append('reportUuid', response.reportUuid);
                                excelFormData.append('hospitalId', response.hospitalId);
                                excelFormData.append('demandYear', response.demandYear);

                                // 上传需求清单
                                $.ajax({
                                    url: '/api/tasks/import',
                                    type: 'POST',
                                    data: excelFormData,
                                    processData: false,
                                    contentType: false,
                                    success: function() {
                                        successCount++;
                                        checkComplete();
                                    },
                                    error: function() {
                                        uploadCount++;
                                        checkComplete();
                                    }
                                });
                            } else {
                                uploadCount++;
                                checkComplete();
                            }

                            // 检查是否有巡检记录文件
                            const inspectionFile = formData.get('inspectionFile');
                            if (inspectionFile && inspectionFile.size > 0) {
                                const inspectionFormData = new FormData();
                                inspectionFormData.append('file', inspectionFile);
                                inspectionFormData.append('reportId', response.id);
                                inspectionFormData.append('reportUuid', response.reportUuid);
                                inspectionFormData.append('hospitalId', response.hospitalId);
                                inspectionFormData.append('demandYear', response.demandYear);

                                // 上传巡检记录
                                $.ajax({
                                    url: '/api/inspections/import',
                                    type: 'POST',
                                    data: inspectionFormData,
                                    processData: false,
                                    contentType: false,
                                    success: function() {
                                        successCount++;
                                        checkComplete();
                                    },
                                    error: function() {
                                        uploadCount++;
                                        checkComplete();
                                    }
                                });
                            } else {
                                uploadCount++;
                                checkComplete();
                            }

                            // 检查是否有巡检记录文件
                            const faultFile = formData.get('faultFile');
                            if (faultFile && faultFile.size > 0) {
                                const faultFileData = new FormData();
                                faultFileData.append('file', faultFile);
                                faultFileData.append('reportId', response.id);
                                faultFileData.append('reportUuid', response.reportUuid);
                                faultFileData.append('hospitalId', response.hospitalId);
                                faultFileData.append('demandYear', response.demandYear);

                                // 上传巡检记录
                                $.ajax({
                                    url: '/api/faults/import',
                                    type: 'POST',
                                    data: faultFileData,
                                    processData: false,
                                    contentType: false,
                                    success: function() {
                                        successCount++;
                                        checkComplete();
                                    },
                                    error: function() {
                                        uploadCount++;
                                        checkComplete();
                                    }
                                });
                            } else {
                                uploadCount++;
                                checkComplete();
                            }

                            // 检查是否所有上传都完成
                            function checkComplete() {
                                if (uploadCount + successCount >= totalUploads) {
                                    if (successCount === totalUploads) {
                                        handleSuccess(response.reportUuid);
                                    } else if (successCount > 0) {
                                        handlePartialSuccess(response.reportUuid);
                                    } else {
                                        handlePartialNoExcelSuccess(response.reportUuid);
                                    }
                                }
                            }
                        } else {
                            handleError();
                        }
                    },
                    error: function(xhr, status, error) {
                        handleError();
                    }
                });
            });

            // 处理完全成功的函数
            function handleSuccess(reportUuid) {
                Swal.close();
                // 生成报告链接
                const reportUrl = window.location.protocol+"//"+window.location.host + `/homePage/${reportUuid}`;

                // 显示报告链接区域
                $('#reportLink').val(reportUrl);
                $('#viewReportBtn').attr('href', reportUrl);
                $('#reportLinkSection').slideDown();

                // 显示成功提示
                Swal.fire({
                    icon: 'success',
                    title: '报告生成成功',
                    text: '您可以复制链接或直接查看报告',
                    confirmButtonText: '确定'
                });
            }

            // 处理部分成功的函数
            function handlePartialSuccess(reportUuid) {
                Swal.close();
                // 生成报告链接
                const reportUrl = window.location.protocol+"//"+window.location.host + `/homePage/${reportUuid}`;

                // 显示报告链接区域
                $('#reportLink').val(reportUrl);
                $('#viewReportBtn').attr('href', reportUrl);
                $('#reportLinkSection').slideDown();

                Swal.fire({
                    icon: 'warning',
                    title: '部分数据导入失败',
                    text: '报告已创建，但部分Excel数据未导入或导入失败，请稍后重试导入',
                    confirmButtonText: '确定'
                });
            }

            function handlePartialNoExcelSuccess(reportUuid) {
                Swal.close();
                // 生成报告链接
                const reportUrl = window.location.protocol+"//"+window.location.host + `/homePage/${reportUuid}`;

                // 显示报告链接区域
                $('#reportLink').val(reportUrl);
                $('#viewReportBtn').attr('href', reportUrl);
                $('#reportLinkSection').slideDown();

                Swal.fire({
                    icon: 'warning',
                    title: '数据导入失败',
                    text: '报告已创建，但未导入Excel数据，请后续重新导入',
                    confirmButtonText: '确定'
                });
            }

            // 处理错误的函数
            function handleError() {
                Swal.fire({
                    icon: 'error',
                    title: '生成失败',
                    text: '服务器错误，请稍后重试',
                    confirmButtonText: '确定'
                });
            }
        });

        // 复制链接功能保持不变
        function copyReportLink() {
            const linkInput = document.getElementById('reportLink');
            linkInput.select();
            document.execCommand('copy');

            Swal.fire({
                icon: 'success',
                title: '复制成功',
                text: '报告链接已复制到剪贴板',
                showConfirmButton: false,
                timer: 1500
            });
        }

        // 初始化年度选择下拉框
        function initYearSelect() {
            const yearSelect = document.querySelector('select[name="demandYear"]');
            const currentYear = new Date().getFullYear();

            // 添加最近5年的选项
            for (let i = 0; i < 5; i++) {
                const year = currentYear - i;
                const option = document.createElement('option');
                option.value = year.toString();
                option.textContent = year;
                yearSelect.appendChild(option);
            }
        }

        // 初始化医院选择下拉框
        function loadHospitalList() {
            fetch('/hospitals/list')
                .then(response => response.json())
                .then(hospitals => {
                    const select = document.getElementById('hospitalSelect');
                    hospitals.forEach(hospital => {
                        const option = document.createElement('option');
                        option.value = hospital.hospitalId;
                        option.textContent = hospital.hospitalName;
                        option.text = hospital.hospitalName;
                        option.dataset.hospitalId = hospital.hospitalId;
                        option.dataset.hospitalName = hospital.hospitalName;
                        select.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载医院列表失败');
                });
        }

        // 监听医院选择变化
        document.getElementById('hospitalSelect').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            document.getElementById('hospitalId').value = selectedOption.value || '';
        });

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initYearSelect();
            loadHospitalList();
        });
        $(document).ready(function() {
            // 初始化 Select2
            $('#hospitalSelect').select2({
                placeholder: '请选择医院',
                allowClear: true,
                width: '100%'
            });

            // 监听选择变化
            $('#hospitalSelect').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const hospitalId = selectedOption.val();
                const hospitalName = selectedOption.text();
                
                // 设置隐藏的 hospitalId 和 hospitalName 输入
                $('#hospitalId').val(hospitalId);
                $('#hospitalName').val(hospitalName);
            });
        });
    </script>
</body>
</html> 